package com.weyoung.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.coze.openapi.client.chat.*;
import com.coze.openapi.client.chat.message.ListMessageReq;
import com.coze.openapi.client.chat.message.ListMessageResp;
import com.coze.openapi.client.chat.model.*;
import com.coze.openapi.client.connversations.message.model.Message;
import com.coze.openapi.client.connversations.message.model.MessageRole;
import com.coze.openapi.service.service.CozeAPI;
import com.coze.openapi.service.service.chat.ChatMessageService;
import com.weyoung.app.mapper.UserDetailMapper;
import com.weyoung.app.service.CozeService;
import com.weyoung.app.service.VideoTaskManager;
import com.weyoung.common.consatant.exception.ClientException;
import com.weyoung.common.model.dto.app.CozeAnalyzeDTO;
import com.weyoung.common.model.entity.UserDetailDO;
import com.weyoung.common.model.entity.VideoTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CozeServiceImpl implements CozeService {

    @Autowired
    private ChatMessageService chatMessageAPI;

    @Autowired
    private CozeAPI cozeAPI;

    @Autowired
    private VideoTaskManager taskManager;

    @Autowired
    private UserDetailMapper userDetailMapper;

    @Value("${coze.bot-id}")
    private String botID; // 扣子机器人ID

    @Value("${coze.bailian-key}")
    private String key; // 百炼key

    /**
     * 调用扣子工作流图生视频，发起请求
     *
     * @param dto 分析请求DTO
     * @return 对话信息
     */
    public Map<String,String> analyzeContent(CozeAnalyzeDTO dto) {
        try {
            // 获取当前登录用户ID
            String userId = StpUtil.getLoginIdAsString();
//            String userId = "1003";
            log.info("开始处理扣子工作流请求: text={}, imageUrl={}, userId={}", dto.getText(), dto.getImageUrl(), userId);

            // 创建聊天
            CreateChatReq req = CreateChatReq.builder()
                    .botID(botID)
                    .userID(userId)
                    .messages(Collections.singletonList(
                            Message.buildUserQuestionText(dto.getText() + "\n" + "图片地址：" + dto.getImageUrl() + "阿里百炼key："+ key )))
                    .build();

            CreateChatResp chatResp = cozeAPI.chat().create(req);
            Chat chat = chatResp.getChat();
            String chatID = chat.getID();
            String conversationID = chat.getConversationID();
            log.info("聊天创建成功: chatID={}, conversationID={}", chatID, conversationID);

            // 创建任务
            VideoTask task = new VideoTask();
            task.setTaskId(chatID);
            task.setConversationId(conversationID);
            task.setChatId(chatID);
            task.setStatus(chat.getStatus().toString());
            task.setCreateTime(new Date());
            task.setUpdateTime(new Date());
            task.setCompleted(false);
            task.setUserId(userId); // 设置用户ID
            taskManager.addTask(task);

            HashMap<String, String> map = new HashMap<>();
            map.put("chat_id", chatID);
            map.put("conversation_id", conversationID);
            return map;
        } catch (Exception e) {
            log.error("处理扣子工作流请求失败", e);
            throw new RuntimeException("处理扣子工作流请求失败: " + e.getMessage());
        }
    }

    /**
     * 调用扣子工作流图生视频，生成关系树视频
     *
     * @return 视频URL
     */
    public Map<String, String> getVideoUrl() {
        int currentUserId = StpUtil.getLoginIdAsInt();
//        int currentUserId = 1003;
        String videoUrl = userDetailMapper.selectById(currentUserId).getGeneratedVideoUrl();
        if (videoUrl == null || videoUrl.isEmpty()) {
            throw new ClientException("未找到用户的图生视频地址，还在生成中，请稍后。。。");
        }
        Map<String, String> videoUrlMap = new HashMap<>();
        videoUrlMap.put("videoUrl", videoUrl);
        return videoUrlMap;
    }

    @Scheduled(fixedDelay = 120000) // 每2分钟执行一次
    public void checkVideoTasks() {
        log.info("开始检查视频生成任务");
        Map<String, VideoTask> tasks = taskManager.getAllTasks();
        
        for (VideoTask task : tasks.values()) {
            if (task.isCompleted()) {
                continue;
            }

            try {
                // 发送查询消息
                CreateChatReq followUpReq = CreateChatReq.builder()
                        .botID(botID)
                        .userID(task.getUserId()) // 使用任务中的用户ID
                        .conversationID(task.getConversationId())
                        .messages(Collections.singletonList(
                                Message.buildUserQuestionText("视频生成好了吗？")))
                        .build();

                CreateChatResp followUpResp = cozeAPI.chat().create(followUpReq);
                Chat chat = followUpResp.getChat();
                String newChatId = chat.getID();
                task.setStatus(chat.getStatus().toString());
                task.setUpdateTime(new Date());

                // 等待回答
                boolean hasResponse = false;
                int maxRetries = 5;
                int retryCount = 0;

                while (!hasResponse && retryCount < maxRetries) {
                    try {
                        // 等待10秒后查询回答
                        TimeUnit.SECONDS.sleep(10);
                        
                        // 获取最新的消息列表
                        ListMessageResp messageResp = chatMessageAPI.list(ListMessageReq.of(task.getConversationId(), newChatId));
                        List<Message> messages = messageResp.getMessages();

                        for (Message message : messages) {
                            if (MessageRole.ASSISTANT.equals(message.getRole())) {
                                String content = message.getContent();
                                log.info("收到回答: {}", content);
                                hasResponse = true;

                                // 首先尝试解析为JSON
                                try {
                                    JSONObject jsonObject = JSON.parseObject(content);
                                    if (jsonObject.containsKey("video_url") && !jsonObject.getString("video_url").isEmpty()) {
                                        String videoUrl = jsonObject.getString("video_url");
                                        task.setVideoUrl(videoUrl);
                                        task.setCompleted(true);
                                        log.info("任务完成，视频URL: {}", videoUrl);
                                        
                                        // 更新数据库中的视频URL
                                        userDetailMapper.updateGeneratedVideoUrl(Integer.parseInt(task.getUserId()), videoUrl);
                                        log.info("已更新用户ID: {} 的视频URL到数据库", task.getUserId());
                                        
                                        // 从任务管理器中移除已完成的任务
                                        taskManager.removeTask(task.getTaskId());
                                        log.info("已从任务管理器中移除任务: {}", task.getTaskId());
                                        break;
                                    }
                                } catch (Exception e) {
                                    // 如果不是JSON格式，直接检查文本内容
                                    if (content.contains("video_url")) {
                                        // 尝试从文本中提取video_url
                                        int startIndex = content.indexOf("video_url") + "video_url".length();
                                        int endIndex = content.indexOf("\"", startIndex + 2);
                                        if (endIndex > startIndex) {
                                            String videoUrl = content.substring(startIndex + 3, endIndex);
                                            if (!videoUrl.isEmpty()) {
                                                task.setVideoUrl(videoUrl);
                                                task.setCompleted(true);
                                                log.info("从文本中提取到视频URL: {}", videoUrl);
                                                
                                                // 更新数据库中的视频URL
                                                userDetailMapper.updateGeneratedVideoUrl(Integer.parseInt(task.getUserId()), videoUrl);
                                                log.info("已更新用户ID: {} 的视频URL到数据库", task.getUserId());
                                                
                                                // 从任务管理器中移除已完成的任务
                                                taskManager.removeTask(task.getTaskId());
                                                log.info("已从任务管理器中移除任务: {}", task.getTaskId());
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        retryCount++;
                    } catch (InterruptedException e) {
                        log.error("等待回答被中断", e);
                        break;
                    }
                }

                if (!hasResponse) {
                    log.warn("未收到回答，将在下次定时任务中重试");
                }

                taskManager.updateTask(task);
            } catch (Exception e) {
                log.error("检查任务失败: taskId={}", task.getTaskId(), e);
            }
        }
    }
}